/**
 *
 */

(function ($) {
    $.fn.spfGrid = function(options , params) {
        //方法判断
        if (typeof options === 'string' && igGridMethod[options] ) {
            //如果是方法，则参数第一个为函数名，从第二个开始为函数参数
            return igGridMethod[options].apply(this , [params]);
        }else if(typeof options === 'object' || !options){
            //调用初始化方法
            return igGridMethod.init.apply(this, arguments);
        }else if($(this).data().spfGrid){
            return $(this).data().spfGrid;
        }
    }

    var igGridMethod = {
        init:function(options){
            var dom = this,
                columns = [],
                columnSettings = [],
                sortSettings = [],
                sourceMode,
                toolbarOpts = [] ,
                groupCols = [] ,
                recordColumnKey ,
                dataType ,
                ds;


            //已经初始化过的grid调用本接口只需要refresh
            if($(dom).data("igGrid")){
                $(dom).spfGrid("refresh") ;
                return ;
            }
           

            //默认id hidden
            columns.push({key:'rowObjectId' , hidden:true}) ;
            columns.push({key:'id' , hidden:true}) ;

            /*
             * 默认的提交方式为post提交
             */
            if(options.mode == 'ext' || options.mode == 'jqgrid'){
                options.requestType = options.requestType ?  options.requestType : "GET" ;
            }else{
                options.requestType = options.requestType ?  options.requestType : "POST" ;
            }

            options.primaryKey  = options.primaryKey ?  options.primaryKey : "rowObjectId" ;
            dataType  = options.dataType ?  options.dataType : "remote" ;
            options.width  = options.width ?  options.width : "100%" ;
            sourceMode = options.mode ? options.mode.toLowerCase() : null ;
            if(sourceMode == 'ext'){
                options.responseDataKey  = options.responseDataKey ?  options.responseDataKey : "result" ;
            }else{ //igGrid和以前的jqGrid都使用GenericDefaultPage对象进行返回数据的接收
                options.responseDataKey  = options.responseDataKey ?  options.responseDataKey : "rows" ;
            }

            if(!options.height || options.height == 'auto') {
                var wh = $(window).height()-98-28;
                var oh = 0;
                var $g = $(dom);
                var rows=$('.grid-other');
                for(var i=0;i<rows.length;i++){
                    var h=$(rows[i]).outerHeight(),
                    mt=parseInt($(rows[i]).css('marginTop')),
                    mb=parseInt($(rows[i]).css('marginBottom')),
                    sum=h+mt+mb;
                    oh+=sum;
                }
                //while ($g.parent()[0].tagName != 'BODY') {
                //    $g.nextAll().each(function () {
                //        if (!$(this).is(":hidden") && $(this).attr("spf-iggrid-ignore") != 'true')
                //            oh += $(this).height();
                //    });
                //    $g.prevAll().each(function () {
                //        if (!$(this).is(":hidden") && $(this).attr("spf-iggrid-ignore") != 'true')
                //            oh += $(this).height();
                //    });
                //    $g = $g.parent();
                //}
                var newH = wh-oh;

                if( $g.parents().hasClass('main-grid-h')){
                    var obj=$g.parents('.main-grid-h');
                    var sib=$('.grid-sib');
                    var sum=0;
                    for(var i=0;i<sib.length;i++){
                    var h=$(sib[i]).outerHeight(),
                        mt=parseInt($(sib[i]).css('marginTop')),
                            mb=parseInt($(sib[i]).css('marginBottom')),
                            num=h+mt+mb;
                        sum+=num;
                     }
                    options.height=newH-sum-5;
                    }
                   else{options.height = newH;}
                    }

            if(options.setHeightFn){
                options.height = options.setHeightFn() ;
            }

            if(options.minHeight){
                var minHeight = parseInt(options.minHeight) ;
                if(isNaN(minHeight)){
                    throw new Error("minHeight设置有误！") ;
                }

                var height = parseInt(options.height) ;
                if(isNaN(height)){
                    throw new Error("height设置有误！") ;
                }

                if(height < minHeight){
                    options.height = minHeight ;
                }
            }


            for(var i in options.columns){
                var igCol = {},
                    colSetting = {} ,
                    sortSetting = {},
                    thisCol = options.columns[i] ;

                igCol.headerText = thisCol.text ? thisCol.text : null ;
                igCol.formatter = thisCol.renderer ? thisCol.renderer : null ;
                igCol.sortable = sortSetting.allowSorting = thisCol.sortable  ;
                sortSetting.columnKey = colSetting.columnKey = igCol.key = thisCol.dataIndex ? thisCol.dataIndex.replace(/\./g, '_') : null ;
                igCol.filterIndex = thisCol.filterIndex ? thisCol.filterIndex : colSetting.columnKey ;
                igCol.headerKey = colSetting.columnKey + "_" + i ;
                igCol.width = settingFn._getHeaderWidth(thisCol) ;

                if(thisCol.group && thisCol.group.length > 0){ //多表头
                    igCol.group = settingFn._settingMultiHeader(thisCol ,columnSettings , sortSettings) ;
                    settingFn._clearParentSetting(thisCol) ;
                    igCol.key = "spf_group_col_" + new Date().getTime() ;
                    groupCols.push(igCol) ;
                }


                settingFn._settingAlign(thisCol,colSetting , igCol) ;
                settingFn._settingFormatter(thisCol ,colSetting, igCol) ;
                settingFn._settingFilter(thisCol,colSetting , igCol) ;


                columns.push($.extend({} ,thisCol ,igCol)) ;
                columnSettings.push(colSetting) ;
                sortSettings.push(sortSetting) ;
            }


            //----------------------------------------------------------------------------features setting end ...........................
            var features= [] ;

            //合并单元格
            if(options.mergeCell === true){
                features.push({
                    name: "CellMerging",
                    initialState: "merged"
                })
            }

            for(var toolbarIndex in options.toolbar){
                var toolbarOpt = {} ;
                toolbarOpt.text = options.toolbar[toolbarIndex].text ;
                toolbarOpt.btnClass = options.toolbar[toolbarIndex].btnClass ;
                toolbarOpt.proxyHandler = function (evt) {
                    var rowObjects = $(dom).spfGrid("getSelection") ,ui = this;
                    if(evt && $(evt.target) && $(evt.target).data("handler")){

                        $(evt.target).data("handler")(rowObjects , ui) ;
                    }
                }
                toolbarOpt.handler = options.toolbar[toolbarIndex].handler ;
                toolbarOpts.push(toolbarOpt) ;
            }

            if(options.mode === 'ext'){
                recordColumnKey = 'totalCount' ;
            }else{
                recordColumnKey = 'records' ;
            }

           // var _isPaging=options._isPaging;
           //  if(_isPaging==false){
           //      features.pop({
           //          name: "Paging",
           //      }) ;
           //  }

            //分页
            if(!options.paging || options.paging === true){
                features.push({
                    name: "Paging",
                    type : dataType ,
                    pageSizeDropDownLocation: "inpager",//这个配置可以把显示多少条数据放在grid的底下
                    recordCountKey: recordColumnKey,
                    pageSizeList : [20,50,100,200,500,2000,10000,20000] ,
                    pageCountLimit: 0 ,
                    pageSizeDropDownLabel: "每页显示 ",
                    pageSizeDropDownTrailingLabel: "",
                    nextPageLabelText: "",
                    prevPageLabelText: "",
                    currentPageDropDownLeadingLabel: "第",
                    currentPageDropDownTrailingLabel: "页，共${count}页",
                    pagerRecordsLabelTemplate: "显示${startRecord}-${endRecord}条，共${recordCount}条",
                    pageSize: options.pageSize || 20  ,
                    toolbar:toolbarOpts
                }) ;
            }

            //列宽自动大小
            if(!(options.disabledResizing === true)){
                features.push({
                    name: "Resizing"
                }) ;
            }

            //列移动
            if(!(options.disabledColumnMoving === true)){
                features.push( {
                    name: "ColumnMoving"
                }) ;
            }

            //排序
            if(!(options.disabledSorting === true)){
                features.push( {
                    name: "Sorting",
                    type: dataType,
                    columnSettings:sortSettings ,
                    mode: "single",
                    persist: true
                }) ;
            }

            //全选
            if(!(options.disabledSelector === true)){
                features.push({
                    name: "Selection" ,
                    activation : false ,
                    mouseDragSelect : false ,
                    multipleCellSelectOnClick : true ,
                    allowMultipleRangeSelection : true ,
                    touchDragSelect : false ,
                    multipleSelection: true,
                    persist : false ,
                    rowSelectionChanging: function(evt,ui){
                        if(ui.startIndex != undefined && ui.endIndex != undefined) return true;
                        var id = ui.row.id;
                        if(id) {
                            var ds = $(this).igGrid().data("igGrid").dataSource;
                            var obj = ds.findRecordByKey(id);
                            var fnc = $("#" + ui.owner.grid.id()).data("rowSelectable");
                            if(fnc) return fnc(obj);
                        }
                        return true;
                    }
                }) ;

                var rowSelectors = {
                    name: "RowSelectors",
                    rowSelectorColumnWidth : 80 ,
                    selectorHeaderText: '序号',
                    requireSelection: true
                } ;

                if(options.enableCheckBoxes === false){
                    rowSelectors.enableCheckBoxes = false ;
                    rowSelectors.rowSelectorColumnWidth = 60 ;
                }else{
                    rowSelectors.enableCheckBoxes = true ;
                }

                if(options.enableRowNumbering === false){
                    rowSelectors.enableRowNumbering = false
                    rowSelectors.rowSelectorColumnWidth = 40 ;
                }else{
                    rowSelectors.enableRowNumbering = true ;   //默认显示,
                }
                features.push(rowSelectors) ;
            }

            // features.push({
            //     name: "Summaries" ,
            //     type: "local" ,
            //     defaultDecimalDisplay: 2 ,
            //     calculateRenderMode: "onselect" ,  //去掉通过确定，取消按钮来计算和隐藏统计信息
            //     dialogButtonOKText: "确定" ,
            //     dialogButtonCancelText: "取消" ,
            //     featureChooserText: "统计" ,
            //     featureChooserTextHide: "统计"
            //
            // }) ;


            //悬浮操作列
            if(options.actionColumn && options.actionColumn.length > 0){
                var actionColumn = options.actionColumn ;
                for(var actionIndex in actionColumn){
                    actionColumn[actionIndex].labelColor = actionColumn[actionIndex].labelColor || "#fff" ;
                }
                features.push({
                        name: "Updating",
                        editMode: null,
                        enableAddRow: false,
                        enableDeleteRow:false ,
                        columnSettings: [
                            {
                                columnKey: "rowObjectId",
                                readOnly: false
                            }
                        ] ,
                        actionRowSettings:options.actionColumn
                    }) ;
            }

            //filter
            var filterOpt = {
                name: "Filtering",
                filterDelay : 1000 ,
                persist: true,
                featureChooserText: "模糊查询",
                featureChooserTextHide: "模糊查询",
                columnSettings: columnSettings,

                labels: {
                    clear: "重置",
                    contains: "模糊查询",

                    on: "=",
                    after: ">",
                    before: "<",

                    greaterThan: "大于",
                    greaterThanOrEqualTo: "大于或等于",
                    lessThan: "小于",
                    equals: "等于",
                    lessThanOrEqualTo: "小于或等于"

                },
                nullTexts: {
                    contains: "模糊查询",

                    on: "=",
                    after: ">",
                    before: "<",

                    greaterThan: "大于",
                    greaterThanOrEqualTo: "大于或等于",
                    lessThan: "小于",
                    equals: "等于",
                    lessThanOrEqualTo: "小于或等于"
                },
                type: dataType,
                mode: 'simple'
            }
            features.push(filterOpt);

            if(groupCols && groupCols.length > 0){
                features.push({
                    name: "MultiColumnHeaders"
                })
            }
            //----------------------------------------------------------------------------features setting end ...........................

            //----------------------------------------------------------------------------dataSource setting start ...........................
            if(!options.url || options.dataSource){
                ds = options.dataSource ;
            }else{
                var paging  ;
                if(options.mode === 'jqgrid'){
                    paging = {
                        enabled: true,
                        pageIndexUrlKey:'page' ,
                        pageSizeUrlKey:'rows' ,
                        startUrlKey:'start' ,
                        type: dataType
                    }
                }else{
                    paging = {
                        enabled: true,
                        pageIndexUrlKey:'page' ,
                        pageSizeUrlKey:'size' ,
                        startUrlKey:'start' ,
                        type: dataType
                    }
                }

                var dataSourceDefaultOpt = {
                    responseDataType: "json",
                    paging:$.extend({} ,paging , options.pager)
                } ,
                    dataSourceOpt = {};

                dataSourceOpt.dataSource = options.url ;
                dataSourceOpt.sourceMode = sourceMode ;
                dataSourceOpt.sortorder = options.sortorder ;
                dataSourceOpt.localSchemaTransform = false ;
                dataSourceOpt.primaryKey  = options.primaryKey || "rowObjectId" ;
                if(options.mode == 'ext' || options.mode == 'jqgrid'){
                    dataSourceOpt.requestType = options.requestType || 'GET' ;
                }else{
                    dataSourceOpt.requestType = options.requestType || 'POST' ;
                }
                dataSourceOpt.filtering = {
                    type: dataType,
                    filterExprUrlKey: "filter"
                } ;
                dataSourceOpt.queryFields = options.queryFields ;
                var dataSourceOpt = $.extend({} , dataSourceOpt , dataSourceDefaultOpt) ;
                ds = new $.spfDataSource(dataSourceOpt);
            }

            //----------------------------------------------------------------------------dataSource setting end ...........................
            options.groupCols = groupCols ;
            var igGridOpt = $.extend({} ,options , {
                virtualization: true, //虚拟化技术
                virtualizationMode: 'continuous',//虚拟化技术
                rowVirtualization:true ,
                columns : columns ,
                features:features ,
                dataSourceType:'json' ,
                localSchemaTransform:false ,
                autoGenerateColumns : false ,
                dataSource: ds
            }) ;

            //在表格渲染后把图片放进去
            igGridOpt.dataRendered = function(evt, ui){
                var $table = $(evt.target) , $container = $table.parent() ,$tBody  = $table.find("tbody"), $trs ;
                if ($tBody && $tBody.length > 0) {
                    $trs = $tBody.find("tr");
                    if ($trs && $trs.length > 0) {
                        $container.removeClass("spf-iggrid-no-data-img");
                    }else{
                        $container.addClass("spf-iggrid-no-data-img");
                    }
                }else{
                    $container.addClass("spf-iggrid-no-data-img");
                }

                if(options.dataRendered){
                    options.dataRendered(evt, ui) ;
                }
            }

            $(dom).igGrid(igGridOpt) ;

            if(!(options.initFilter === true)){
                //igGird在初始化的时候会把模糊查询初次加载，因此需要在其对象渲染后把模糊查询隐藏
                $(dom).igGridFiltering("toggleFilterRowByFeatureChooser") ;
            };

            if(igGridOpt.rowSelectable){
                $(dom).on("iggridselectionrowselectionchanging", function(){return true;});
                $(dom).data("rowSelectable",igGridOpt.rowSelectable);
            }

        } ,
        //解析dataSource的extraParams参数，因为filter在某些情况下可能会被禁用，因此不能在filter上解析extraParams，只好增加一个参数传入
        load:function(params){
            var ds = $(this).igGrid("option", "dataSource");
            ds.settings.extraParams = params ;
            $(this).igGridPaging("pageIndex", 0);  //刷新数据
            delete ds.settings.extraParams ; //数据刷新完了后需要清除extraParams
        } ,
        //刷新grid的数据
        refresh :function(){
            var optinos = $(this).igGrid("option") , dataType;
            if(optinos === undefined){
                throw new Error("grid未初始化") ;
            }
            dataType = optinos.dataType ;
            if(dataType === 'local'){
                $(this).igGrid("dataBind");  //点击查询，分页统一显示为0
            }else{
                $(this).igGridPaging("pageIndex", 0);  //点击查询，分页统一显示为0
            }
        },

        setData:function(data){
            if(undefined === data || null === data){
                return ;
            }

            if(data.constructor.name === "Array"){
            	for(var i = 0 ; i < data.length ; i++){
            		if(undefined != data[i] && null != data[i]){
            			data[i].rowObjectId =  i;
            		} ;
            	}
            	
                $(this).igGrid("dataSourceObject", {
                    rows:data,
                    records:data.length}).igGrid("dataBind");
            }


        } ,
        //清除filter条件
        clear:function(){
            $(this).igGridFiltering("filter" , [])
        } ,
        getSelectionIds :function(){
            return $(this).igGridSelection('selectedRows');
        },
        getSelection :function(){
            var ds = $(this).igGrid().data("igGrid").dataSource , ids = $(this).igGridSelection('selectedRows') ,results = [] ;
            for(var i = 0 ; i < ids.length ; i++){
                results.push(ds.findRecordByKey(ids[i]["id"])) ; //selector的值为primaryKey设置的值
            }
            return results;
        } ,
        selectionSize : function(){
            var rows = $(this).igGridSelection('selectedRows'); ;
            return rows ? rows.length : 0 ;
        },
        isExists:function(){
        	if($(this).data("igGrid")){
        		return true ;
        	}else{
        		return false ;
        	}
        } ,
        getRequestParams: function(params){
            var ds = $(this).igGrid().data("igGrid").dataSource  ,
                requestUrl = '' , query;
            if(ds){
                requestUrl = ds._lastParams ;
                if(params && requestUrl && requestUrl.query){
                    $.each(params , function(k , v){
                        requestUrl.query.push({property:k , value:v}) ;
                    }) ;

                }
            }
            return requestUrl ;
        }  ,
        getByRowObjectId:function(rowObjectId){
            if(rowObjectId === undefined || rowObjectId === null || rowObjectId === ''){
                return null ;
            }
            var ds = $(this).igGrid().data("igGrid").dataSource  ;
            if(typeof rowObjectId === 'number'){
                rowObjectId = rowObjectId + "" ;
            }else if(typeof rowObjectId === 'string'){
                //nothing to do
            }else{
                return null ;
            }


            return ds.findRecordByKey(rowObjectId) ; //selector的值为primaryKey设置的值
        }
    }

    $.spfDataSource = $.spfDataSource || $.ig.RemoteDataSource.extend({
        init: function (options) {
            if (!options) {
                options = {}
            }
            options.settings = $.extend({} ,this.settings , options.settings) ;
            this._super(options);
            return this
        } ,_encodeExtraParams:function(params){
                var extraParams = this.settings.extraParams ,
                    queryFields = this.settings.queryFields,
                    queries = [] ,
                    i ,
                    sourceMode = this.settings.sourceMode;

                if(queryFields && queryFields.length > 0 ){
                    this._buildQueryParams(queryFields , queries) ;
                }

                if (extraParams) {
                    if(typeof extraParams === 'object'){
                        $.each(extraParams , function(k , v){
                            var query = {} ;
                            query.property = k;
                            query.value = v ;
                            queries.push(query) ;
                        }) ;
                    }
                }

                if(sourceMode == 'ext'){  //如果配置了Ext type才会去构造Ext的请求参数
                    params.extraParams.query = JSON.stringify(queries) ;
                }else if(sourceMode == 'jqgrid'){
                   for(i = 0 ; i < queries.length ; i++){
                	    if(queries[i].property){
                	    	params.extraParams[queries[i].property] = queries[i].value ;
                	    }
                   }
                }else{
                    params.extraParams.query = queries ;
                }
        } ,
        /*
         * 重写filter的插件
         * 我们需要构造成
         * 1、ExtGrid类
         *
         * 2、IgGrid类
         * [{"operator":"like","value":"23","property":"employeeCommInsureProductViewVO_idCard"}]类，后台使用IgRequestObject对象接受
         * 这样一种形式的对象
         */
        _encodeFilteringParams:function(params){
            var f = this.settings.filtering,
                sourceMode = this.settings.sourceMode ? this.settings.sourceMode : null ,
                ffields,
                i,
                exprNotReq,
                cond,
                expr,
                fieldName;

            f.expressions = f.expressions || [] ;

            if (f.type === "remote") {
                if (f.exprString) {
                    ffields = this._parseFilterExprString(f.exprString)
                } else {
                    //获取到配置的filter的expressions属性
                    ffields = f.expressions
                }

                var filters = [] ;

                for (i = 0; i < ffields.length; i++) {
                    var filter = {} ;
                    this._isFilteringReq = true;
                    cond = ffields[i].cond;
                    exprNotReq = this._isFilteringExprNotReq(cond);
                    //如果配置了filterExprUrlKey属性，就只有设置到$filter，否则则为""


                    fieldName = ffields[i].fieldName;
                    expr = ffields[i].expr;

                    filter.property = fieldName ? fieldName : null;
                    filter.value = expr ;


                    //如果配置了contains则代表是模糊查询
                    if (ffields[i].cond && ffields[i].cond.toLowerCase() === "contains") {
                        filter.operator = 'like';
                    } else if (ffields[i].cond && ffields[i].cond.toLowerCase() === "is") {
                        filter.operator = 'is';
                    }else if (ffields[i].cond && ffields[i].cond.toLowerCase() === "lessthan") { //小于
                        filter.operator = 'lt';
                    } else if (ffields[i].cond && ffields[i].cond.toLowerCase() === "equals") { //等于
                        filter.operator = 'eq';
                    } else if (ffields[i].cond && ffields[i].cond.toLowerCase() === "greaterthan") { //大于
                        filter.operator = 'gt';
                    }else if (ffields[i].cond && ffields[i].cond.toLowerCase() === "greaterthanorequalto") { //大于或等于
                        filter.operator = 'gte';
                    }else if (ffields[i].cond && ffields[i].cond.toLowerCase() === "lessthanorequalto") { //小于或等于
                        filter.operator = 'lte';
                    }else if (ffields[i].cond && ffields[i].cond.toLowerCase() === "list") { //小于或等于
                        filter.operator = 'in';
                    }else if (ffields[i].cond && ffields[i].cond.toLowerCase() === "on") { //小于或等于
                        filter.operator = 'eq';
                    }else if (ffields[i].cond && ffields[i].cond.toLowerCase() === "after") { //小于或等于
                        filter.operator = 'gt';
                    }else if (ffields[i].cond && ffields[i].cond.toLowerCase() === "before") { //小于或等于
                        filter.operator = 'lt';
                    }


                    if(sourceMode == 'jqgrid'){
                        if(filter.operator == 'gt'){
                            params.filteringParams[fieldName + "_gt"] = expr ;
                        }else if(filter.operator == 'lt'){
                            params.filteringParams[fieldName + "_lt"] = expr ;
                        }else{
                            params.filteringParams[fieldName] = expr ;
                        }

                    }else{
                        filters.push(filter) ;
                    }

                }

                if(sourceMode == 'ext'){  //如果配置了Ext type才会去构造Ext的请求参数
                    params.filteringParams.filter = JSON.stringify(filters) ;
                }else if(sourceMode == 'jqgrid'){
                    //nothing to do
                }else{
                    params.filteringParams.filters = filters ;
                }


            }
        },

        /**
         * 自定义分页参数
         * @param params
         * @private
         */
        _encodePagingParams: function (params) {
            var p = this.settings.paging;
            if (p.enabled && p.type === "remote") {
                this._isPagingReq = true;
                if (p.pageIndexUrlKey !== null && p.pageSizeUrlKey !== null && p.startUrlKey) {
                    params.pagingParams[p.pageIndexUrlKey] = this.pageIndex();
                    params.pagingParams[p.pageSizeUrlKey] = this.pageSize() ;
                    params.pagingParams[p.startUrlKey] = this.pageSize() * this.pageIndex() ;
                } else {
                    throw new Error("paging params is missing!!!") ;
                }
            }
        },

        /**
         * 自定义排序参数
         * @param params
         * @private
         */
        _encodeSortingParams:function(params){
            var s = this.settings.sorting, tmpdir, i, sfields, url, urlQS, hlayout = null,
                sourceMode = this.settings.sourceMode ? this.settings.sourceMode : null,
                sortorder = this.settings.sortorder ? this.settings.sortorder : null;
            if (s.type === "remote") {
                if (s.exprString) {
                    sfields = this._parseSortExpressions(s.exprString)
                } else {
                    sfields = s.expressions
                }
                this._isSortingReq = true;
                if(sfields.length == 0 && sortorder &&  sortorder.sort && sortorder.sidx){
                    if(sourceMode == 'jqgrid'){
                        if (params.sortingParams.sord === undefined) {
                            params.sortingParams.sord =  sortorder.sort
                        }
                    }else{
                        if (params.sortingParams.sort === undefined) {
                            params.sortingParams.sort =  sortorder.sort
                        }
                    }
                    if (params.sortingParams.sidx === undefined) {
                        params.sortingParams.sidx = sortorder.sidx
                    }
                }else{
                    for (i = 0; i < sfields.length; i++) {
                        if (s.sortUrlAscValueKey !== null && s.sortUrlDescValueKey !== null && s.sortUrlKey !== null) {
                            tmpdir = sfields[i].dir && sfields[i].dir.toLowerCase().startsWith("asc") ? s.sortUrlAscValueKey : s.sortUrlDescValueKey;
                            params.sortingParams[s.sortUrlKey + "(" + sfields[i].fieldName + ")"] = tmpdir
                        } else {
                            if(sourceMode == 'jqgrid'){
                                if (params.sortingParams.sord === undefined) {
                                    params.sortingParams.sord =  sfields[i].dir.toLowerCase()
                                }
                            }else{
                                if (params.sortingParams.sort === undefined) {
                                    params.sortingParams.sort =  sfields[i].dir.toLowerCase()
                                }
                            }
                            if (params.sortingParams.sidx === undefined) {
                                params.sortingParams.sidx = sfields[i].sidx
                            }
                        }
                    }
                }

            }
        } ,
            _encodeSelectParams:function(){
              //override _encodeSelectParams method
            } ,
        /**
         * 构建表头查询参数
         * 可配置参数
         * 1、id:查询dom input的id
         * 2、name:checkBox 或 radio 的时候会使用name来获取到数组
         * 3、dataIndex: 传到后台的参数
         *
         *
         * ~~~~原则：
         * 1、如果配置的是字符串，则默认使用dom的id来获取其值.
         * 2、如果配置的是一个object，优先获取id，再获取name.
         */
        _buildQueryParams:function(queryFields , queries){
            for(var queryIndex in queryFields){
                var query = {},
                    queryField = queryFields[queryIndex],
                    fieldSelector ,
                    fieldName,
                    fieldValue;

                if(typeof queryField == 'string'){
                    fieldName = queryFields[queryIndex] ;
                    fieldSelector = "#" + queryFields[queryIndex] ;
                }else{
                    if(queryField.id){
                        fieldSelector = "#" + queryFields[queryIndex].id ;
                    }else if(queryField.name){
                        fieldSelector = "input[name = '" + queryFields[queryIndex].name + "']" ;
                        if($(fieldSelector).length <= 0){ //不存在值就获取select
                            fieldSelector = "select[name = '" + queryFields[queryIndex].name + "']" ;
                            if($(fieldSelector).length <= 0){ //不存在值就获取textarea
                                fieldSelector = "textarea[name = '" + queryFields[queryIndex].name + "']" ;
                                if($(fieldSelector).length <= 0) {
                                    throw new Error("no this name!!!!");
                                }
                            }
                        }
                        fieldSelector = $(fieldSelector)[0] ;
                    }else{
                        throw new Error("not setting name or id!!!!") ;
                    }

                    fieldName = queryFields[queryIndex].dataIndex || queryFields[queryIndex].id || queryFields[queryIndex].name ;

                    if(!fieldName){
                        throw new Error("Must setting dataIndex or id or name") ;
                    }

                }

                if($(fieldSelector).prop('tagName').toLowerCase()  == 'input' || $(fieldSelector).prop('tagName').toLowerCase() == 'select' || $(fieldSelector).prop('tagName').toLowerCase() == 'textarea'){
                    var type =  $(fieldSelector).attr('type') ? $(fieldSelector).attr('type').toLowerCase() : null ;
                    if(type && ( type == 'checkbox' || type == 'radio')){
                        if(!queryField.name){
                            throw new Error("checkBox or radio must set name") ;
                        }
                        fieldValue = [] ;
                        $("input[name='" + queryField.name + "']:checked").each(function(){
                            fieldValue.push($(this).val()) ;
                        }) ;
                    }else {
                        fieldValue = $(fieldSelector).val();
                    }
                } else{
                    throw new Error("unknown tag name") ;
                }

                /**
                 * 需要增加一个转化器，把值进行转换
                 */
                if(queryField.convertFunc){
                    fieldValue = queryField.convertFunc(fieldValue) ;
                }


                if(fieldName != undefined && fieldName != null && fieldName != ''){
                    query.property = fieldName ;
                    query.value = fieldValue ;
                    queries.push(query) ;
                }

            }
        }

    });


})(jQuery);

var filter = {
    string:{
        dataType:'string'
    },
    number:{
        dataType:'number'
    },
    bool:{
        dataType:'bool'
    },
    date:{
        dataType:'date'
    },
    month:{
        dataType:'month'
    }
}

var actionBgColor = {
    query:'#6CCAC9',
    upload:'#57c8f2',
    insert:'#FF913A',
    update:'#8075C4' ,
    delete:'#FF6C60',
    fix:'#54C7F6'

}

var fn = {
    //金额格式化
    money : function (s, n) {
        if (undefined != s && null != s && '' !== s) {
            if (isNaN(s)) {   //如果s不是数字，直接返回原字符串
                return s;
            }

            n = n > 0 && n <= 20 ? n : 2;
            s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
            var l = s.split(".")[0].split("").reverse(),
                r = s.split(".")[1];
            var t = "";
            for (var i = 0; i < l.length; i++) {
                if ((l[i] == '-') && (t.charAt(t.length - 1) == ',')) {
                    t = t.substring(0, t.length - 1);
                }

                t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
            }
            return t.split("").reverse().join("") + "." + r;
        }
        else {  //如果传入空的s，则直接返回空
            return "";
        }
    } ,
    mergeCell : function(rowObject , list , convert){
        if (rowObject === undefined && rowObject === null && rowObject === '') {
            return "";
        }
        var tdHeight = 30;
        if (rowObject.constructor.name == 'Array') {
            var result = "<div class='bt-0'><table  class='ui-table-bortop-none' border='0' cellspacing='0'  cellpadding='0' style='padding: 0px;border:none;' width='100%'>";
            for (var i = 0; i < rowObject.length; i++) {

                var columnVal = convert(rowObject[i]) ;

                if (undefined === columnVal || null === columnVal || '' === columnVal) {
                    columnVal = '';
                }

                if (rowObject.length == 1) {
                    result += "<tr><td height=" + tdHeight + "><span style='font-weight:normal'>" + columnVal + "</span></td></tr>";
                } else {
                    if (i == rowObject.length - 1) {
                        result += "<tr><td style='border-bottom:0px;border-right: 0px' height=" + tdHeight + "><span style='font-weight:normal'>" + columnVal + "</span></td></tr>";
                    } else if (i == 0) {
                        result += "<tr><td style='border-top:0px;border-right: 0px' height=" + tdHeight + "><span style='font-weight:normal'>" + columnVal + "</span></td></tr>";
                    } else {
                        result += "<tr><td style='border-top:0px;border-right: 0px' height=" + tdHeight + "><span style='font-weight:normal'>" + columnVal + "</span></td></tr>";
                    }
                }
            }
            result += "</table></div>";
            return result;
        } else {
            return rowObject;
        }
    }
}

var settingFn = {
    _getHeaderWidth:function(thisCol){
        if(thisCol.width || thisCol.group || thisCol.hidden){
            return ;
        }

        if(thisCol.hidden != true && (thisCol.text === undefined || thisCol.text === null)){
            throw new Error("column没有配置为hidden时必须配置text") ;
        }

        var  i , char , text = thisCol.text  , headerLength = 0 ;
        for(i = 0 ; i < text.length ; i++){
            char = text[i] ;
            if(this._isChinese(char)){
                headerLength += 16 ;
            }else{
                headerLength = 8 ;
            }
        }

        return headerLength + 50 ;
    } ,
    _isChinese:function(char){
        return new RegExp("[\\u4E00-\\u9FFF]+","g").test(char);
    } ,
    _settingFilter: function (thisCol, colSetting , igCol) {
        if (thisCol.filter) { //设置了filter
            switch (thisCol.filter.dataType) {
                case 'string' :
                    colSetting.conditionList = ["contains"];//字符串类的目前只包含模糊查询
                    break;
                case 'number' :
                    colSetting.conditionList = ["lessThan", "equals", "greaterThan"];//数字类型的只包含等于，大于，小于
                    break;
                case 'bool' :
                    break;
                case 'date' :
                    colSetting.conditionList = ["on", "before", "after"];//日期类型的只包含等于，大于，小于
                    colSetting.dateFilter = {type: 'date', format: 'yyyy-mm-dd'};  //自定义属性
                    break;
                case 'month':
                    colSetting.conditionList = ["on", "before", "after"];//日期类型的只包含等于，大于，小于
                    colSetting.dateFilter = {type: 'month', format: 'yyyy-mm-dd'};  //自定义属性
                    break;
                case 'object' :
                    break;
                default:
                    throw new Error("not has this filter type!!!");
            }
        } else {
            colSetting.allowFiltering = false;
        }

        var filterDataType = thisCol.filter ? thisCol.filter.dataType : 'string' ;
        if(filterDataType == 'month'){  //过滤器本身不支持month，这个是为了兼容month而写的配置，因此需要转换回去
            filterDataType = 'date' ;
        }

        //filter 自定义设置
        igCol.dataType = thisCol.dataType || filterDataType ;
    },
    _settingAlign: function (thisCol,colSetting, igCol) {
        //居左居中居右设置
        var defaultColumnCls = 'ui-spf-cell-font' ;
        thisCol.align = thisCol.align ? thisCol.align : 'left';
        switch (thisCol.align) {
            case 'left' :
                igCol.columnCssClass = 'ui-spf-columns-align-left ' + defaultColumnCls;
                break;
            case 'center' :
                igCol.columnCssClass = 'ui-spf-columns-align-center ' + defaultColumnCls;
                break;
            case 'right' :
                igCol.columnCssClass = 'ui-spf-columns-align-right ' + defaultColumnCls;
                break;
            default:
                console.error("not has this align type!!!");
        }
    },
    _settingFormatter: function (thisCol,colSetting, igCol) {
        //如果列配置了renderer或format，则formatType属性失效
        if (!(thisCol.renderer || thisCol.format || thisCol.formatter) && thisCol.formatType) {
            //如果是month格式的，则直接调用插件中的format配置，money是系统自定义格式，需要调用money方法进行格式化
            switch (thisCol.formatType) {
                case 'month' :
                    igCol.format = 'yyyy-MM';
                    thisCol.dataType = 'date' ;
                    break;
                case 'date' :
                    igCol.format = 'yyyy-MM-dd';
                    thisCol.dataType = 'date' ;
                    break;
                case 'money' :
                    igCol.formatter = function (val, record) {
                        return fn.money(val, 2);
                    };
                    break;
                default:
                    throw new Error("not has this filter type!!!");
            }
        }
    } ,
    //递归设置表头
    _settingMultiHeader:function(thisCol ,columnSettings , sortSettings){
        var childIgCol = {} ,
            childColSetting  ,
            childSortSetting  ,
            childDataIndex ,
            group = thisCol.group ,
            childCols = [];
        for(var childIndex in group){
            childColSetting = {} ;
            childSortSetting = {} ;
            childDataIndex = group[childIndex] ;

            childIgCol.headerText = childDataIndex.text ? childDataIndex.text : null ;
            childIgCol.formatter = childDataIndex.renderer ? childDataIndex.renderer : null ;
            childSortSetting.columnKey = childColSetting.columnKey = childIgCol.key = childDataIndex.dataIndex ? childDataIndex.dataIndex.replace(/\./g, '_') : null ;
            childIgCol.sortable = childSortSetting.allowSorting = thisCol.sortable  ;
            childIgCol.filterIndex = childDataIndex.filterIndex ? childDataIndex.filterIndex : childColSetting.columnKey ;
            childIgCol.headerKey = childColSetting.columnKey + "_c_" + childIndex ;
            childIgCol.isChild = true ;
            childIgCol.width = settingFn._getHeaderWidth(childDataIndex) ;

            this._settingAlign(childDataIndex ,childColSetting, childIgCol) ;
            this._settingFormatter(childDataIndex,childColSetting , childIgCol) ;
            this._settingFilter(childDataIndex,childColSetting , childIgCol) ;
            childColSetting.isChildCol = true ;

            if(childDataIndex.group && childDataIndex.group.length > 0){
                childIgCol.group =  this._settingMultiHeader(childDataIndex ,columnSettings , sortSettings) ;
                this._clearParentSetting(childDataIndex) ;
                childDataIndex.key = "spf_group_col_" + new Date().getTime() ;
            }

            columnSettings.push(childColSetting) ;
            childCols.push($.extend({} ,childDataIndex , childIgCol)) ;
        }
        return childCols ;
    } ,
    //多表头列表上清除多余的列配置
    _clearParentSetting:function(thisCol){
        delete thisCol.width  ;
        delete thisCol.sortable  ;
        delete thisCol.align  ;
        delete thisCol.sidx  ;
        delete thisCol.filterIndex  ;
        delete thisCol.formatType  ;
        delete thisCol.filter  ;
    }
}

